const bucket = new WeakMap();

const data = {
  text: 'hello world'
};

let activeEffect
// effect 函数用于注册副作用函数
function effect(fn) {
  // 当调用 effect 注册副作用函数时，将副作用函数 fn 赋值给 activeEffect
  activeEffect = fn
  // 执行副作用函数
  fn()
}


const obj = new Proxy(data, {
  get(target, key) {
    track(target, key);
    return target[key]
  },
  set(target, key, newVal) {
    target[key] = newVal;
    trigger(target, key)
  }
});

// 依赖收集，bucket格式为 bucket => target:map; map => key:set 
function track(target, key) {
  if (!activeEffect) return;
  let depsMap = bucket.get(target);

  if (!depsMap) {
    bucket.set(target, (depsMap = new Map()))
  }

  let deps = depsMap.get(key);

  if (!deps) {
    depsMap.set(key, deps = new Set())
  }
  deps.add(activeEffect);
  activeEffect = null; // 重置
}


function trigger(target, key) {
  const depsMap = bucket.get(target)
  if (!depsMap) return;

  const effects = depsMap.get(key)
  effects && effects.forEach(fn => fn())

}

effect(() => {
  console.log(1)
  document.body.innerText = obj.text;
});

// effect(() => {
//   let domA = document.querySelector('.cha4_data_key_A');
//   domA.innerText = obj.notExist;
// })

setTimeout(() => {
  obj.text = 'hello vue3';
  obj.notExist = "a not exist property"
}, 1000);

// setTimeout(() => {
//   let domA = document.querySelector('.cha4_data_key_A');
//   domA.innerText = obj.notExist;
// }, 2000);